<script setup>
import { reactive, ref, onMounted } from 'vue'

import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import wlsPopup from '@/components/common/wls-popup.vue'
import dingwei from '@/assets/img/dingwei.png'
import { area, layerInfo, specieNameList, locationMedia, uploadResource } from "@/utils/api.js"
import olMap from "ol/Map";
import View from "ol/View";
import * as olProj from "ol/proj";
import { Vector as VectorSource, XYZ } from "ol/source";
import { Tile as TileLayer, Image as ImageLayer, Vector as VectorLayer } from "ol/layer";
import { defaults as defaultControls, OverviewMap } from 'ol/control';
import ImageWMS from 'ol/source/ImageWMS';
import { Circle as CircleStyle, Fill, Stroke, Style, Text, Icon } from 'ol/style';
import GeoJSON from "ol/format/GeoJSON";
import Overlay from "ol/Overlay";

let container = null;
let PopOverlay = null;
import "ol/ol.css";

import delimg from '@/assets/img/del.png'
import shipin from '@/assets/img/shipin.jpg'
import ypimg from '@/assets/img/nwav.png'
const emit = defineEmits(['refreshcar'])
const token = ref('')
const olm = ref(null)
const loading = ref(false)
const uploadRef = ref(null)
const actionUrl = ref('null')
const ivlist = ref([])
let upl = [];
const fileList = ref([])
const disabled = ref(false)

const zhonglist = ref([]);
const options = ref([])
const ruleForm = reactive({
    keywords: "",
    recordTime: '',
    resourceType: "animal",
    place: "",
    lon: '',
    lat: '',
    alt: 0,
})

const rules = reactive({
    lon: [{ required: true, message: '请输入经度', trigger: 'blur' }],
    lat: [{ required: true, message: '请输入纬度', trigger: 'blur' }],
    alt: [{ required: true, message: '请输入海拔', trigger: 'blur' }],
    resourceType: [
        {
            required: true,
            message: '请选择物种类型',
            trigger: 'change',
        },
    ]
})

const ruleFormRef = ref(null)
let imeiList = [];
const isup = ref(false);

const delu = (file) => {
    ivlist.value.splice(file, 1);
}

const remoteMethod = (query) => {
    if (query) {
        let obj = {
            type: '',
            specieType: ruleForm.resourceType,
            zhong: query
        }
        specieNameList(obj).then(res => {
            if (res.code == '200') {
                let arr = [];
                res.data.forEach(e => {
                    let z = {
                        label: e,
                        value: e
                    }
                    arr.push(z)
                })
                setTimeout(() => {
                    zhonglist.value = arr.filter((item) => {
                        return item.label.toLowerCase().includes(query.toLowerCase())
                    })
                }, 200)
            }
        })

    } else {

        zhonglist.value = options.value;
    }
}

const getspecieNameList = async () => {
    let obj = {
        type: '',
        specieType: ruleForm.resourceType,
        zhong: ""
    }
    let res = await specieNameList(obj)
    if (res.code == '200') {
        let arr = [];
        res.data.forEach(e => {
            let z = {
                label: e,
                value: e
            }
            arr.push(z)
        })
        zhonglist.value = arr;
    }
}

const cameraup = (event) => {
    let file = event.target.files;
    for (let i = 0; i < file.length; i++) {
        let imgUrl = URL.createObjectURL(file[i]);
        let z = {
            id: file[i].lastModified,
            file: file[i],
            url: imgUrl,
            type: file[i].type
        }
        ivlist.value.push(z)
    }
    event.target.value = '';
}


const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (ivlist.value.length > 0) {
                loading.value = true
                const formData = new FormData();
                formData.append("areaId", areaId);
                formData.append("recordTime", (ruleForm.recordTime && ruleForm.recordTime != '') ? Date.parse(ruleForm.recordTime) : '');
                formData.append("workUser", JSON.parse(window.sessionStorage.getItem('usermsg')).zhName);
                formData.append("lon", ruleForm.lon);
                formData.append("lat", ruleForm.lat);
                formData.append("alt", ruleForm.alt);
                formData.append("keywords", ruleForm.keywords);
                formData.append("resourceType", ruleForm.resourceType);
                formData.append("place", ruleForm.place);

                ivlist.value.forEach(e => {
                    formData.append("files", e.file);
                })

                uploadResource(formData).then(res => {
                    if (res.code == '200') {
                        ElMessage({
                            type: 'success',
                            message: res.message,
                        })
                        formEl.resetFields();
                        emit('refreshcar', '')
                        isup.value = false
                        loading.value = false

                    } else {
                        ElMessage({
                            type: 'warning',
                            message: err.message,
                        })
                    }
                })
                    .catch(err => {
                        ElMessage({
                            type: 'warning',
                            message: err.message,
                        })
                    })
            } else {
                ElMessage({
                    type: 'warning',
                    message: '请选择要上传的文件',
                })
            }


        } else {
            console.log('error submit!', fields)
        }

    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
    ruleForm.keywords = '';
    ruleForm.resourceType = '';
    ruleForm.place = '';
    emit('refreshcar', '')
    isup.value = false
    loading.value = false
}

const open = (item) => {
    totalMap = {};
    ivlist.value = [];
    getspecieNameList();
    isup.value = true
    setTimeout(function () {
        getarea();
    }, 1000)
}


let areaId = '';
let identifyUser = '';
const base = ref([]);
const other = ref([]);
const lw = ref(0)
const radio = ref('天地图');
const checkList = ref([]);
let mapmls = null;
let totalMap = {};
let vectorSource = null;

const SwitchLayers = (data) => {
    if (lw.value == data) {
        lw.value = 0;
    } else {
        lw.value = data;
    }
}

const getarea = async () => {
    let res = await area(areaId)
    if (res) {
        let d = res.data.mapConfig;
        init(d.lon, d.lat, d.level);

    }
}

const getlayerInfo = async () => {
    let params = {
        areaId: areaId,
        userId: ""
    }
    let res = await layerInfo(params)
    if (res.code == '200') {
        let arrAy = [], arrAy2 = [];
        arrAy = res.data.base;
        base.value = arrAy;
        base.value.forEach(e => {
            if (e.name === '天地图') {
                addXYZ('baseLayer', e.layerUrl)
            }
        })
        arrAy2 = res.data.other;
        other.value = arrAy2;
        other.value.forEach(e => {
            if (e.selected) {
                drawWMS(e.id, e.layerUrl, e.layerName, e.styleId, e.cql);
                checkList.value.push(e.name)
            }
        })
    }
}

const previewshape = (data, id) => {
    //判断是否已经存在相同id的图层 如果有删掉，再重新绘制
    if (typeof (totalMap[id]) != "undefined") {
        mapmls.removeLayer(totalMap[id]);
        delete totalMap[id];
    }
    let styleFunction = function () {
        return function (feature, resolution) {
            //点
            if (feature.getGeometry().getType() == 'Point') {
                if (feature.get('fillColor').indexOf('#') != -1) {
                    var point = new Style({
                        image: new CircleStyle({
                            radius: feature.get("radius"),
                            fill: new Fill({
                                color: feature.get("fillColor")
                            }),
                            stroke: new Stroke({
                                color: feature.get("borderColor"),
                                width: feature.get("size")
                            })
                        }),
                        text: new Text({
                            font: '16px Microsoft YaHei',
                            text: feature.get('name'),
                            fill: new Fill({
                                color: '#4C4ADD'
                            }),
                            offsetY: 15,
                            stroke: new Stroke({
                                color: 'rgba(0,0,0,0)',
                                width: 0
                            }),
                        })
                    })
                } else {
                    var point = new Style({
                        image: addImage(feature, resolution),
                        text: new Text({
                            font: '14px Microsoft YaHei',
                            text: feature.get('name'),
                            fill: new Fill({
                                color: '#387BFF'
                            }),
                            offsetY: 15,
                            stroke: new Stroke({
                                color: '#fff',
                                width: 1
                            }),
                        })
                    })
                }
                return [point]
            }
            if (feature.getGeometry().getType() == 'MultiPoint') {
                var MultiPoint = new Style({
                    image: new CircleStyle({
                        radius: 5,
                        fill: new Fill({
                            color: feature.get("fillColor")
                        }),
                        stroke: new Stroke({
                            color: feature.get("borderColor"),
                            width: feature.get("size")
                        })
                    }),
                    text: new Text({
                        font: '12px Calibri,sans-serif',
                        text: feature.get('text'),
                        fill: new Fill({
                            color: feature.get('fillColor')
                        }),
                        offsetY: 15,
                        stroke: new Stroke({
                            color: 'white',
                            width: 1
                        }),
                    })
                })
                return [MultiPoint]
            }
            //面
            if (feature.getGeometry().getType() == 'MultiPolygon') {
                var MultiPolygon = new Style({
                    stroke: new Stroke({
                        color: feature.get('borderColor'),
                        width: feature.get("size")
                    }),
                    fill: new Fill({
                        color: feature.get("fillColor")
                    }),
                    text: new Text({
                        font: '16px Calibri,sans-serif',
                        text: feature.get('text'),
                        fill: new Fill({
                            color: feature.get('textColor')
                        }),
                        stroke: new Stroke({
                            color: feature.get('textColor'),
                            width: 1
                        })
                    })
                })
                return [MultiPolygon]
            }
            if (feature.getGeometry().getType() == 'Polygon') {
                var Polygon = new Style({
                    stroke: new Stroke({
                        color: feature.get('borderColor'),
                        width: feature.get("size")
                    }),
                    fill: new Fill({
                        color: feature.get("fillColor")
                    }),
                    text: new Text({
                        font: '12px Calibri,sans-serif',
                        text: feature.get('text'),
                        fill: new Fill({
                            color: feature.get('borderColor')
                        }),
                        stroke: new Stroke({
                            color: 'white',
                            width: 3
                        }),
                    })
                })
                return [Polygon]
            }
            //线
            if (feature.getGeometry().getType() == 'LineString') {
                var LineString = new Style({
                    stroke: new Stroke({
                        color: feature.get('borderColor'),
                        width: 2
                    }),
                    fill: new Fill({
                        color: feature.get("fillColor"),
                        width: 2
                    }),
                    text: new Text({
                        font: '12px Calibri,sans-serif',
                        text: feature.get('text'),
                        fill: new Fill({
                            color: 'white'
                        }),
                        stroke: new Stroke({
                            color: 'block',
                            width: 2
                        }),
                    })
                })
                return [LineString]
            }
            //多线
            if (feature.getGeometry().getType() == 'MultiLineString') {
                var MultiLineString = new Style({
                    stroke: new Stroke({
                        color: feature.get('borderColor'),
                        width: feature.get("size") + 3
                    }),
                    text: new Text({
                        font: '12px Calibri,sans-serif',
                        text: feature.get('text'),
                        fill: new Fill({
                            color: 'white'
                        }),
                        stroke: new Stroke({
                            color: 'block',
                            width: 2
                        }),
                    })
                })
                return [MultiLineString]
            }
        }
    };
    let geojsonObject = {
        'type': 'FeatureCollection',
        'crs': {
            'type': 'name',
            'properties': {
                'name': 'EPSG:4326'
            }
        },
        'features': []
    };
    vectorSource = new VectorSource({
        features: (new GeoJSON(
            {
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            }
        )).readFeatures(geojsonObject)
    });
    totalMap[id] = new VectorLayer({
        source: vectorSource,
        style: styleFunction()
    });
    let sources = totalMap[id].getSource();
    data.forEach((e => {
        sources.addFeatures(
            (new GeoJSON({
                defaultDataProjection: 'EPSG:4326',
                featureProjection: 'EPSG:3857'
            })).readFeatures({
                "id": e.id,
                "properties": {
                    "name": e.name,
                    "borderColor": e.borderColor,
                    "fillColor": e.fillColor,
                    "iconSrc": e.iconSrc,
                    "data": e.data
                },
                'type': 'Feature',
                'geometry': e.geojson
            }))
    }));
    totalMap[id].set("altitudeMode", "clampToGround");
    mapmls.addLayer(totalMap[id]);
    totalMap[id].setZIndex(99)
    // let centerid = data[0].id,
    //     thisfeature = vectorSource.getFeatureById(centerid),
    //     center = thisfeature.getGeometry().getFirstCoordinate();
    // mapmls.getView().setCenter(center);
};
//点类型绘制图标 需要定位图标位置
//地图图标位置处理函数
const addImage = (feature, resolution) => {
    let src = feature.get('iconSrc');
    let anchor = [0, 1];
    //根据图标文件名 设置定位点  地图上放置的图标更改文件名即可保持一致
    if (src != '') {
        if (src.indexOf('anchor_bottom_center') != -1) {
            anchor = [0.5, 1];
        } else if (src.indexOf('anchor_bottom_left') != -1) {
            anchor = [0, 1];
        } else if (src.indexOf('anchor_bottom_right') != -1) {
            anchor = [1, 1];
        } else if (src.indexOf('anchor_center_center') != -1) {
            anchor = [0.5, 0.5];
        } else if (src.indexOf('anchor_top_center') != -1) {
            anchor = [0.5, 0];
        } else if (src.indexOf('anchor_top_left') != -1) {
            anchor = [0, 0];
        } else if (src.indexOf('anchor_top_right') != -1) {
            anchor = [1, 0];
        }
        return new Icon({
            src: feature.get('iconSrc'),
            anchor: [0.5, 1],
            scale: 0.5
        });
    }
};

const init = (lon, lat, level) => {
    let center = [lon, lat]; // 地图的初始中心点
    mapmls = new olMap({
        target: 'mapcontr',
        layers: [],
        overlays: [],
        controls: defaultControls({
            attribution: false,
            zoom: false,
            rotate: false
        }).extend([new OverviewMap()]),
        view: new View({
            //设置中心点
            center: olProj.fromLonLat(center),
            zoom: 11,
        })
    });

    mapmls.on('singleclick', function (evt) {
        let feature = mapmls.forEachFeatureAtPixel(evt.pixel,
            function (feature) {
                return feature;
            });
        var coordinate = olProj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
        ruleForm.lon = coordinate[0];
        ruleForm.lat = coordinate[1];

        previewshape([{
            id: 'hsfhfdh93qysdfbhtyrwe8bhf',
            name: '',
            borderColor: "",
            fillColor: '',
            offsetY: 24,
            iconSrc: dingwei,
            geojson: {
                'type': 'Point',
                'coordinates': coordinate
            }
        }], 'dgdgwgw5354bgdg')

    });

    getlayerInfo();
};

const addXYZ = (item, url) => {
    if (typeof (totalMap[item]) != "undefined") {
        mapmls.removeLayer(totalMap[item]);
        delete totalMap[item];
    }
    totalMap[item] = new TileLayer({
        source: new XYZ({
            url: url
        })
    },
    )
    mapmls.addLayer(totalMap[item])
};

//绘制wms类型
const drawWMS = (item, url, name, styleId, cql) => {
    if (typeof (totalMap[item]) != "undefined") {
        mapmls.removeLayer(totalMap[item]);
        delete totalMap[item];
    } else {
        let params = {
            'LAYERS': name,
            'STYLES': styleId,
            'CQL_FILTER': "[" + cql + "]"
        };

        totalMap[item] = new ImageLayer({
            source: new ImageWMS({
                url: url,
                params: params,
                serverType: 'geoserver'
            })
        })
        mapmls.addLayer(totalMap[item]);
    }
};

onMounted(() => {
    areaId = JSON.parse(window.sessionStorage.getItem('usermsg')).areaId;
    identifyUser = JSON.parse(window.sessionStorage.getItem('usermsg')).zhName;
    token.value = window.sessionStorage.getItem('token')

})

defineExpose({ open })

</script>
<template>
    <wls-popup v-if="isup">
        <div class="wls-u">
            <div class="d-lkb-c" @click.stop="resetForm(ruleFormRef)">
                <i class="icon iconfont icon-guanbi" style="color: #387BFF;font-size:20px;"></i>
            </div>
            <div class="qzTitle">
                <div></div>
                <div><span>上传</span></div>
            </div>

            <div style="width: 100%; height: 680px;margin-top: 16px; display: flex; overflow: hidden;">
                <div style="flex: 1.5;height: 100%;">
                    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="top"
                        class="demo-ruleForm" size="large">
                        <el-row :gutter="10">
                            <el-col :span="8">
                                <el-form-item label="物种类型" prop="resourceType">
                                    <el-select v-model="ruleForm.resourceType" placeholder="请选择类型">
                                        <el-option value="animal" label="动物" />
                                        <el-option value="plant" label="植物" />
                                        <el-option value="fungus" label="真菌" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="物种名称">
                                    <!-- <el-input v-model="ruleForm.keywords" placeholder="请输入物种名称" /> -->
                                    <el-select v-model="ruleForm.keywords" filterable remote
                                        :remote-method="remoteMethod" :loading="loading" placeholder="填选物种名称">
                                        <el-option v-for="item in zhonglist" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="时间">
                                    <el-date-picker v-model="ruleForm.recordTime" type="date" placeholder="请选择时间"
                                        style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <div style="margin-bottom: 16px;">
                            <span style="font-weight: 700;">请输入位置信息</span>
                            <span style="color: #E6A23C;margin-left: 8px;">(为保证位置正确，强烈建议点击地图选择点位位置)</span>
                        </div>

                        <el-row :gutter="10">
                            <el-col :span="8">
                                <el-form-item label="经度">
                                    <el-input v-model="ruleForm.lon" placeholder="格式示例：117.3306" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="纬度">
                                    <el-input v-model="ruleForm.lat" placeholder="格式示例： 40.568069" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="海拔(米)">
                                    <el-input v-model="ruleForm.alt" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-form-item label="小地名">
                            <el-input v-model="ruleForm.place" placeholder="请输入小地名" />
                        </el-form-item>
                    </el-form>
                    <div class="mapcontr" id="mapcontr">
                        <div class="mapmls-menu">
                            <div>
                                <img src="/src/assets/img/l1.png" @click.stop="SwitchLayers(1)" alt="">
                                <div class="mm-layers" v-if="lw == 1">
                                    <el-radio-group v-model="radio">
                                        <el-radio v-for="(i, index) in base" :label="i.name"
                                            @change="addXYZ('baseLayer', i.layerUrl)">{{
                                                i.name }}</el-radio>
                                    </el-radio-group>
                                </div>
                            </div>
                            <div>
                                <img src="/src/assets/img/l2.png" @click.stop="SwitchLayers(2)" alt="">
                                <div class="mm-layers" v-if="lw == 2">
                                    <el-checkbox-group v-model="checkList">
                                        <el-checkbox v-for="(i, index) in other"
                                            @change="drawWMS(i.id, i.layerUrl, i.layerName, i.styleId, i.cql)"
                                            :label="i.name" />
                                    </el-checkbox-group>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>

                <div style="flex: 2;margin-left: 16px;">

                    <!-- <div class="wls-u-btn">
                        <i style="color: var(--wls-color);" class="icon iconfont icon-tianjia1"></i>
                        <span style="margin-left: 0.08rem;">选择文件</span>
                        <input class="wls-upload" @change="cameraup($event, 0)" ref="upload" multiple
                            accept="image/jpeg, image/png, video/*, audio/*" type="file" />
                    </div> -->

                    <div class="wls-u-siv scol" v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)"
                        element-loading-text="文件较多，努力上传中...">
                        <ul class="wls-u-ul">
                            <li class="wls-u-btn">
                                <el-icon style="font-size: 40px;">
                                    <Plus />
                                </el-icon>
                                <input class="wls-upload" @change="cameraup($event, 0)" ref="upload" multiple
                                    :accept="ruleForm.resourceType == 'animal' ? 'image/*, video/*, audio/*' : 'image/*, video/*'"
                                    type="file" />
                            </li>
                            <li v-for="(i, index) in ivlist" :key="i.id">
                                <div class="d-lkb-c" @click.stop="delu(index)" style="top: 0.04rem;right: 0.04rem;">
                                    <img :src="delimg" alt="">
                                </div>
                                <video v-if="i.type.split('/').indexOf('video') != -1" :src="i.url" controls></video>
                                <img v-if="i.type.split('/').indexOf('image') != -1" :src="i.url" alt="">
                                <img v-if="i.type.split('/').indexOf('audio') != -1" :src="ypimg" alt="">
                            </li>
                        </ul>
                    </div>

                    <div style="margin: 16px 0;display: flex;align-items: center;justify-content: center;">
                        <el-button style="background-color: #387BFF;color: #fff;"
                            @click.stop="submitForm(ruleFormRef)">确定</el-button>
                        <el-button @click.stop="resetForm(ruleFormRef)">取消</el-button>
                    </div>

                </div>
            </div>

        </div>
    </wls-popup>
</template>
<style scoped>
.wls-u {
    width: 95%;
    padding: 24px;
    background-color: #fff;
    position: relative;
    overflow: hidden;
}


.d-lkb-c {
    position: absolute;
    top: -5px;
    right: 0;
    z-index: 2;
    cursor: pointer;
}

.wls-u-btn {
    width: 100%;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    color: #aaa;
    border: 1px dashed #aaa;
    background: #fff !important;
    position: relative;
}

.wls-u-siv {
    width: 100%;
    height: calc(100% - 50px)
}

.wls-u-ul {
    width: 100%;
    overflow: hidden;
}

.wls-u-ul li {
    width: calc((100% - 64px) / 5);
    height: 145px;
    float: left;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #000;
    margin: 0 16px 16px 0;
    position: relative;
    overflow: hidden;
}

.wls-u-ul li img {
    width: 100%;
    height: 100%;
}

.wls-u-ul li video {
    max-width: 100%;
    max-height: 100%;
}

.wls-u-ul li:nth-child(5n) {
    margin-right: 0;
}

.mapcontr {
    width: 100%;
    height: 450px;
    position: relative;
}


.mapmls-menu {
    display: flex;
    align-items: center;
    position: absolute;
    top: 16px;
    left: 16px;
    z-index: 22;
    /* overflow: hidden; */
    cursor: pointer;
}

.mapmls-menu>div {
    width: 40px;
    height: 40px;
    margin-left: 16px;
    position: relative;
}

.mapmls-menu>div img {
    width: 100%;
    height: 100%;
}

.mm-layers {
    padding: 20px 0 20px 20px;
    background-color: #FFFFFF;
    border-radius: 4px;
    position: absolute;
    top: 52px;
    left: 0;
    z-index: 2;
    /* overflow: hidden; */
}

.mm-layers::before {
    content: "";
    position: absolute;
    top: -10px;
    left: 20px;
    transform: translateX(-50%);
    width: 0;
    height: 0;
    border-left: 12px solid transparent;
    border-right: 12px solid transparent;
    border-bottom: 12px solid #FFFFFF;
}


.wls-upload {
    display: inline-block;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    opacity: 0;
    cursor: pointer;
}
</style>